package logic

import (
	"bw-renting/common"
	"bw-renting/user-rpc/userclient"
	"context"
	"crypto/md5"
	"fmt"
	"io"
	"log"
	"strconv"
	"time"

	"bw-renting/api/internal/svc"
	"bw-renting/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// TODO: 用户登录
func (l *UserLoginLogic) UserLogin(req *types.UserLoginReq) (resp *types.Data, err error) {
	// todo: add your logic here and delete this line
	//md5加密
	h := md5.New()
	io.WriteString(h, req.Password)
	password := fmt.Sprintf("%x", h.Sum(nil))
	log.Println(password)
	d, _ := l.svcCtx.UserServer.UserLogin(l.ctx, &userclient.UserLoginReq{
		Username: req.Mobile,
		Password: password,
	})
	if d.Code != 200 {
		return &types.Data{
			Code:    int(d.Code),
			Message: d.Message,
		}, nil
	}
	token, _ := common.GetJwtToken(l.svcCtx.Config.AuthToken.AccessSecret, time.Now().Unix(), l.svcCtx.Config.AuthToken.AccessExpire, strconv.FormatInt(d.UserId, 10))
	return &types.Data{
		Code:    int(d.Code),
		Message: d.Message,
		Data: map[string]string{
			"userId": strconv.FormatInt(d.UserId, 10),
			"token":  token,
		},
	}, nil
}
